package com.tobby.camel.camelinaction.chapter5.errorhandler;

import org.apache.camel.Exchange;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.impl.JndiRegistry;
import org.apache.camel.test.spring.CamelSpringTestSupport;
import org.junit.Test;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpringHandleFaultTest extends CamelSpringTestSupport {

	@Override
	protected AbstractApplicationContext createApplicationContext() {
		return new ClassPathXmlApplicationContext(
				"com/tobby/camel/camelinaction/chapter5/errorhandler/HandleFaultTest.xml");
	}

	@Override
	protected JndiRegistry createRegistry() {
		JndiRegistry registry = new JndiRegistry();
		registry.bind("orderService", new OrderService());
		return registry;
	}

	@Test
	public void testOrderOK() throws InterruptedException {
		MockEndpoint endpoint = getMockEndpoint("mock:queue.order");
		endpoint.expectedMessageCount(1);

		template.sendBody("seda:queue.inbox", "amount=1,name=Camel in Action");

		assertMockEndpointsSatisfied();
	}

	@Test
	public void testOrderFail() throws InterruptedException {
		MockEndpoint mock = getMockEndpoint("mock:queue.order");
		mock.expectedMessageCount(0);

		MockEndpoint dead = getMockEndpoint("mock:dead");
		dead.expectedMessageCount(1);
		// and on the EXCEPTION_CAUGHT property we have the caused exception which we can
		// assert contains the fault message
		dead.message(0).exchangeProperty(Exchange.EXCEPTION_CAUGHT)
				.convertTo(String.class).contains("ActiveMQ in Action is out of stock");

		template.sendBody("seda:queue.inbox", "amount=1,name=ActiveMQ in Action");

		assertMockEndpointsSatisfied();
	}

}
